class Comment < ActiveRecord::Base
  belongs_to :requirement, :counter_cache => false
  belongs_to :user
  
  belongs_to :reply,
             :class_name => "Comment",
             :foreign_key => :reply_id
  has_many   :comments,
             :class_name => "Comment",
             :foreign_key => :reply_id

  has_many :favorite_comments
  has_many :lovers,
           :through => :favorite_comments,
           :source => :user

  has_attached_file :attach, 
                          :path => ":rails_root/public/:class/:attachment/:id/:style_:basename.:extension",
                          :url  => "/:class/:attachment/:id/:style_:basename.:extension"
  attr_protected :attach_file_size, :attach_content_type
  validates_attachment_size :attach, :less_than => 5.megabytes, :message => "附件不超过5m"
  validates_attachment_content_type :attach, :content_type => ['application/zip','application/rar'], :message => "请上传zip或rar文件"
  
  validates_numericality_of :price, :message => "为数字"             
  validates_presence_of :user, :requirement, :content, :price, :message => "不能为空"
  validates_length_of :content, :maximum => DB_TEXT_MAX_LENGTH
  validates_uniqueness_of :content, :scope => [:user_id, :requirement_id]
  #如果是重复的评论（用户和正文相同）则返回ture
  def duplicate?
    c = Comment.find_by_requirement_id_and_user_id_and_content(requirement,user,content)
    self.id = c.id unless c.nil?
    not c.nil?
  end
  
  #在删除评论时进行身份认证
  def authorized?(user)
    requirement.user == user
  end
  
  #获取嵌套评论
  def self.get_quote(comment)
    replys = []
    until comment.reply.nil?
      replys<<comment
      comment = comment.reply
    end
    replys<<comment
    replys
  end
end
